<template>
  <div class="product-name-management">
    <div class="page-header">
      <div class="header-left">
        <h2>商品名称管理</h2>
      </div>
      <div class="header-right">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedProductNames.length === 0">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>新建商品名称
        </el-button>
        <el-button type="success" @click="showBulkImportDialog">
          <el-icon><Upload /></el-icon>批量导入
        </el-button>
      </div>
    </div>

    <!-- 查询条件 -->
    <div class="search-panel">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择分类"
            clearable
            style="width: 150px"
          >
            <el-option label="水果" value="水果" />
            <el-option label="蔬菜" value="蔬菜" />
            <el-option label="肉类" value="肉类" />
            <el-option label="粮食" value="粮食" />
            <el-option label="饮料" value="饮料" />
            <el-option label="电子产品" value="电子产品" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><RefreshRight /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 商品名称列表 -->
    <div class="table-container">
      <el-table
        v-loading="loading.productNames"
        :data="productNames"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button-group class="operation-buttons">
              <el-button type="primary" @click="showEditDialog(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                :type="row.is_active ? 'warning' : 'success'" 
                @click="handleToggleStatus(row)"
              >
                <el-icon><SwitchButton /></el-icon>
                {{ row.is_active ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建/编辑商品名称对话框 -->
    <el-dialog
      v-model="dialogs.productName"
      :title="editingProductName.id ? '编辑商品名称' : '新建商品名称'"
      width="550px"
    >
      <el-form
        ref="productNameFormRef"
        :model="editingProductName"
        :rules="productNameRules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="editingProductName.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="editingProductName.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="水果" value="水果" />
            <el-option label="蔬菜" value="蔬菜" />
            <el-option label="肉类" value="肉类" />
            <el-option label="粮食" value="粮食" />
            <el-option label="饮料" value="饮料" />
            <el-option label="电子产品" value="电子产品" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="editingProductName.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch
            v-model="editingProductName.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.productName = false">取消</el-button>
          <el-button type="primary" :loading="loading.submit" @click="handleSubmitProductName">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="dialogs.bulkImport"
      title="批量导入商品名称"
      width="600px"
    >
      <div class="bulk-import-dialog">
        <el-alert
          type="info"
          show-icon
          :closable="false"
          title="请按照JSON格式输入商品名称数据，每行一个商品名称对象"
        />
        <p class="format-example">格式示例：<code>[{"name": "苹果", "category": "水果", "description": "常见水果"}, {"name": "香蕉", "category": "水果"}]</code></p>
        <el-input
          v-model="bulkImportData"
          type="textarea"
          :rows="10"
          placeholder="请输入JSON格式的商品名称数据"
          @input="validateBulkImportData"
        />
        <div v-if="bulkImportError" class="json-error">
          <el-alert
            type="error"
            show-icon
            :closable="false"
            :title="bulkImportError"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.bulkImport = false">取消</el-button>
          <el-button type="primary" :loading="loading.bulkImport" @click="handleBulkImport">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Edit, Delete, Search, RefreshRight, Upload, SwitchButton
} from '@element-plus/icons-vue'
import { 
  getProductNameList, 
  createProductName, 
  updateProductName, 
  deleteProductName,
  bulkCreateProductNames,
  bulkUpdateProductNameStatus
} from '@/api/config'

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  is_active: ''
})

// 多选相关
const selectedProductNames = ref([])

// 状态变量
const productNames = ref([])
const editingProductName = ref({
  name: '',
  category: '其他',
  description: '',
  is_active: true
})
const bulkImportData = ref('')
const bulkImportError = ref('')

// 加载状态
const loading = reactive({
  productNames: false,
  submit: false,
  bulkImport: false,
  batchDelete: false
})

// 对话框显示状态
const dialogs = reactive({
  productName: false,
  bulkImport: false
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单引用
const productNameFormRef = ref(null)

// 表单验证规则
const productNameRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 初始化
onMounted(() => {
  fetchProductNameList()
})

// 获取商品名称列表
const fetchProductNameList = async () => {
  try {
    loading.productNames = true
    
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize
    }
    
    if (searchForm.name) {
      params.name = searchForm.name
    }
    
    if (searchForm.category) {
      params.category = searchForm.category
    }
    
    if (searchForm.is_active !== '') {
      params.is_active = searchForm.is_active
    }
    
    const response = await getProductNameList(params)
    
    if (response) {
      // 处理后端直接返回数组的情况
      if (Array.isArray(response)) {
        productNames.value = response
        pagination.total = response.length
      } 
      // 处理后端返回对象包含items的情况
      else if (response && response.items) {
        productNames.value = response.items
        pagination.total = response.total
      } else {
        productNames.value = []
        pagination.total = 0
      }
    } else {
      productNames.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取商品名称列表失败:', error)
    ElMessage.error('获取商品名称列表失败')
    productNames.value = []
    pagination.total = 0
  } finally {
    loading.productNames = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  editingProductName.value = {
    name: '',
    category: '水果',
    description: '',
    is_active: true
  }
  dialogs.productName = true
}

// 显示编辑对话框
const showEditDialog = (productName) => {
  editingProductName.value = { ...productName }
  dialogs.productName = true
}

// 提交商品名称表单
const handleSubmitProductName = async () => {
  try {
    await productNameFormRef.value.validate()
    
    loading.submit = true
    
    if (editingProductName.value.id) {
      // 更新现有商品名称
      await updateProductName(editingProductName.value.id, editingProductName.value)
      ElMessage.success('商品名称更新成功')
    } else {
      // 创建新商品名称
      await createProductName(editingProductName.value)
      ElMessage.success('商品名称创建成功')
    }
    
    dialogs.productName = false
    fetchProductNameList()
  } catch (error) {
    console.error('保存商品名称失败:', error)
    ElMessage.error('保存商品名称失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    loading.submit = false
  }
}

// 删除商品名称
const handleDelete = async (productName) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品名称 "${productName.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteProductName(productName.id)
    ElMessage.success('商品名称删除成功')
    fetchProductNameList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品名称失败:', error)
      ElMessage.error('删除商品名称失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 切换商品名称状态
const handleToggleStatus = async (productName) => {
  try {
    const newStatus = !productName.is_active
    const actionText = newStatus ? '启用' : '禁用'
    
    await ElMessageBox.confirm(
      `确定要${actionText}商品名称 "${productName.name}" 吗？`,
      `${actionText}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: newStatus ? 'success' : 'warning'
      }
    )
    
    await updateProductName(productName.id, { is_active: newStatus })
    ElMessage.success(`商品名称已${actionText}`)
    fetchProductNameList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新商品名称状态失败:', error)
      ElMessage.error('更新商品名称状态失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1 // 重置到第一页
  fetchProductNameList()
}

// 重置查询
const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  searchForm.is_active = ''
  pagination.currentPage = 1
  fetchProductNameList()
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchProductNameList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchProductNameList()
}

// 多选处理
const handleSelectionChange = (selection) => {
  selectedProductNames.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedProductNames.value.length === 0) {
    ElMessage.warning('请选择要删除的商品名称')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedProductNames.value.length} 个商品名称吗？此操作不可恢复。`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.batchDelete = true
    
    // 逐个删除商品名称
    const promises = selectedProductNames.value.map(item => deleteProductName(item.id))
    await Promise.all(promises)
    
    ElMessage.success(`成功删除 ${selectedProductNames.value.length} 个商品名称`)
    selectedProductNames.value = []
    fetchProductNameList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除商品名称失败:', error)
      ElMessage.error('批量删除商品名称失败')
    }
  } finally {
    loading.batchDelete = false
  }
}

// 显示批量导入对话框
const showBulkImportDialog = () => {
  bulkImportData.value = ''
  bulkImportError.value = ''
  dialogs.bulkImport = true
}

// 验证批量导入数据
const validateBulkImportData = (value) => {
  if (!value.trim()) {
    bulkImportError.value = ''
    return
  }
  
  try {
    const data = JSON.parse(value)
    if (!Array.isArray(data)) {
      bulkImportError.value = '数据格式错误：应为JSON数组'
      return
    }
    
    for (const item of data) {
      if (!item.name) {
        bulkImportError.value = '数据格式错误：商品名称不能为空'
        return
      }
    }
    
    bulkImportError.value = ''
  } catch (error) {
    bulkImportError.value = 'JSON格式错误: ' + error.message
  }
}

// 批量导入商品名称
const handleBulkImport = async () => {
  if (bulkImportError.value) {
    ElMessage.error('请修正数据格式错误')
    return
  }
  
  if (!bulkImportData.value.trim()) {
    ElMessage.warning('请输入商品名称数据')
    return
  }
  
  try {
    loading.bulkImport = true
    
    const data = JSON.parse(bulkImportData.value)
    const response = await bulkCreateProductNames({ items: data })
    
    ElMessage.success(`成功导入 ${response.created_count} 个商品名称`)
    if (response.error_count > 0) {
      ElMessage.warning(`有 ${response.error_count} 个商品名称导入失败`)
    }
    
    dialogs.bulkImport = false
    fetchProductNameList()
  } catch (error) {
    console.error('批量导入商品名称失败:', error)
    ElMessage.error('批量导入商品名称失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    loading.bulkImport = false
  }
}
</script>

<style scoped>
.product-name-management {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0;
}

.header-right {
  display: flex;
  gap: 10px;
}

.search-panel {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.operation-buttons {
  display: flex;
  flex-wrap: nowrap;
}

.bulk-import-dialog {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.format-example {
  font-size: 14px;
  color: #606266;
}

.format-example code {
  background-color: #f5f7fa;
  padding: 2px 5px;
  border-radius: 3px;
  font-family: monospace;
}

.json-error {
  margin-top: 10px;
}
</style> 